import sys
import os
import pylab as plt
from params import *

def avg(seq):
    if not seq:
        return 0.0
    else:
        return float(sum(seq))/len(seq)

fig_width_pt = 246.0  # Get this from LaTeX using \showthe\columnwidth
inches_per_pt = 1.0/72.27               # Convert pt to inch
golden_mean = (sqrt(5)-1.0)/2.0         # Aesthetic ratio
fig_width = fig_width_pt*inches_per_pt  # width in inches
fig_height = fig_width*golden_mean      # height in inches
fig_size =  [fig_width,fig_height]
params = {'backend': 'ps',
        'axes.labelsize': 12,
        'text.fontsize': 10,
        'legend.fontsize': 10,
        'xtick.labelsize': 12,
        'ytick.labelsize': 12,
        'lines.markersize': 3,  
        'lines.mfc': 'g',  
        'text.usetex': True,
        'figure.figsize': fig_size}
pylab.rcParams.update(params)

DIR = os.path.join(WORKDIR, 'gsn', 'cpp', 'limelight', 'results')
DIR = os.path.join(WORKDIR, 'gsn', 'cpp', 'limelight', 'results_new')
def extract_params(filename):
    try:
        params = filename[:-4].split('_')
        cache, weight,size = map(int,params[2:5])
        traffic_prob = float(params[5])
        retweet = float(params[6])
        r = {}
        r['cache_mode'] = cache
        r['weight_mode'] = weight
        r['cache_size'] = size
        r['traffic_ratio'] = traffic_prob
        r['retweet'] = retweet

        return r
    except:
        return None

def compare(cache1,weight1,cache2,weight2):
    data1 = {}
    data2 = {}
    data = None
    for file in os.listdir(DIR):
        params = extract_params(file)
        ok = False
        if not params:
            continue
        cache_mode = params['cache_mode']
        weight_mode = params['weight_mode']

        retweet_ratio = params['retweet']
        size = params['cache_size']
        if retweet_ratio == 0:
            continue
        if retweet_ratio > 0.005:
            continue

        if cache_mode == cache1 and weight_mode == weight1:
            data = data1
            ok = True

        if cache_mode == cache2 and weight_mode == weight2:
            data = data2
            ok = True

        if not ok:
            continue
        print file
    
        if not retweet_ratio in data:
            data[retweet_ratio] = {}
        if not size in data[retweet_ratio]:
            data[retweet_ratio][size] = []

        total_hits = 0
        total_misses = 0
        total_cold = 0
        first = True
        print file
        for line in open(os.path.join(DIR,file)):
            if first:
                first = False
                num_req, num_videos = map(int,line.split(';'))
                continue

            server,name,hits,misses,cold_misses = line.split(';')
            h,m,c = map(int,(hits,misses,cold_misses))
            total_hits += h
            total_misses += m
            total_cold += c
            if m:
                hit_ratio = 1.0*h/(h+m-c)
            else:
                hit_ratio = 0
            #print 'Server %s hit ratio %f'%(name,hit_ratio)
        #gain on infinite cache
        total_hit_ratio = 1.0*total_hits/(total_hits+total_misses-total_cold)
        data[retweet_ratio][size].append(total_hit_ratio)


    plt.figure()
    plt.clf()
    FIG_AXES = [0.10,0.2,0.95-0.12,0.95-0.2]
    plt.axes(FIG_AXES2)
    lbl = []
    for retweet_ratio,marker,color in zip(sorted(data1),markers, colors):
        x,y = [],[]
        print retweet_ratio
        for size in sorted(data1[retweet_ratio]):
            x.append(size)
            v1 = avg(data1[retweet_ratio][size])
            v2 = avg(data2[retweet_ratio][size])
            gain = 100.0*(v2/v1-1)
            #gain = v2-v1
            y.append(gain)
        plt.plot(x,y,'%s%s-'%(color, marker), markersize=5, mec=color,mfc='None')
        lbl.append('p = %.3f'%retweet_ratio)

    plt.xlabel('Cache size [\%]')
    plt.ylabel('Gain [\%]')
    plt.grid(True)
    plt.legend(lbl,loc='upper right',ncol=2,
            numpoints=1,markerscale=1.0,
            columnspacing=0.15)
    loc,labels = plt.xticks()
    new_labels = map(lambda x: '$%.2f$'%(float(100*x)/1e6),loc)
    plt.xticks(loc,new_labels)
    [x0,x1,y0,y1] = plt.axis()
    plt.axis([x0,x1,0.0,100.0])
    plt.savefig('cache_gain_%d_%d_%d_%d.pdf'%(
        cache1,weight1,cache2,weight2))
    plt.close()


if __name__ == '__main__':
    caches = [0,1,2]
    for cache in caches:
        compare(cache,0,cache,1)
        compare(cache,0,cache,2)
        compare(cache,1,cache,2)
